// pages/todayTask/todayTask.js
import {FIG_Ble,Ble_Tools} from "../../ble/Ble"
import {Cocos_Api_MG} from "../../ble/Cocos_Api_MG"
import {Quaternion} from "../../ble/ab"
import Message from "../../miniprogram_npm/tdesign-miniprogram/message/index"
import {GETSTORAGE, SETSTORAGE} from "../../services/storage/storage"
import {addRecoveryRecord,getMedicalRecord} from "../../services/_utils/api"
var util = require('../../utils/util')
var action = ''
function calculateAngleBetweenQuaternions(q1, q2) {
  // 计算两个四元数之间的差异四元数
  let deltaQ = q1.multiply(q2.conjugate());
  // 使用差异四元数的w值来计算夹角
  let angle = 2 * Math.acos(deltaQ.w);
  // 转换为度
  let angleInDegrees = angle * (180.0 / Math.PI);
  return angleInDegrees;
}
var app = getApp()
var degVal
var updataVal = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    devices:[],
    okDevices:[],//已连接设备列表
    degrees:'0',//度数
    maxFlag:false,
    minFlag:false,
    extend:false,//伸
    bend:false, //屈
    extendNum:0,//伸次数
    bendNum:0,//屈次数
    bendFlag:false,
    extendFlag:false,
    trainLeg:'左腿',//哪条腿
    thighDevice1:'',//大腿设备Id
    shankDevice1:'',//小腿设备Id
    thighDevice2:'',//大腿设备Id
    shankDevice2:'',//小腿设备Id
    trainFlag:false,//能否开始训练状态
    popFlag:false,
    timer2: null,//定时器
    nowTime: '00:00:00', // 计时
    hour: 0,//小时
    minutes: 0,//分钟
    seconds: 0 ,//秒
    selectPop:false,//选择设备弹出框
    checkList:[],//选择到的设备
    searchFlag:false,//搜索中
  },
  watch:{
    'degrees':function(oldVal,newVal){
      // if(list.length>100){
      //   console.log(list,'=========');
      //   return
      // }
      // list.push(newVal)
      // if(30<newVal && newVal<100){
      //   action='缓冲'
      //   console.log(action,this.data.degrees,'=============');
      // }
      if(newVal<oldVal && oldVal != 0 && oldVal>90){
        console.log(oldVal,'===========屈========');
        this.setData({
          extend:true,
          bend:false
        })
        if(oldVal>100){
          this.handleSubmit('屈',oldVal)
        }
      }
      if(newVal>oldVal && oldVal != 0 && oldVal<90){
        this.setData({
          extend:false,
          bend:true
        })
        if(oldVal<30){
          this.handleSubmit('伸',oldVal)
        }
      }
    }
  },
  // 获取病历表信息
  getMedicalRecordInfo(){
    const memberInfoId = GETSTORAGE('recoveryMemberInfoId')
    getMedicalRecord({recoveryMemberInfoId:memberInfoId}).then(res => {
      console.log(res,'病历表信息');
      const index = res.data.data.length-1
      console.log(index);
      if(res.data.data[index].leftLeg){
        this.setData({
          trainLeg:'左腿'
        })
      }
      if(res.data.data[index].rightLeg){
        this.setData({
          trainLeg:'右腿'
        })
      }
    })
  },
  // 选择设备
  checkChange(e){
    console.log(e,'选择到的设备');
    const {value} = e.detail
    this.setData({
      checkList:value
    })
  },
  // 确定选择设备
  handleOk(){
    if(this.data.checkList.length == 2){
      console.log('连接');
      const obj = {
        currentTarget:{
          dataset:{
            item:this.data.checkList[0]
          }
        }
      }
      const obj1 = {
        currentTarget:{
          dataset:{
            item:this.data.checkList[1]
          }
        }
      }
        this.connect(obj)
       updataVal = obj1
     this.handleCance()
    }else{
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '请选择两个设备',
      });
      console.log('请选择两个');
    }
  },
  // 取消选择设备
  handleCance(){
    this.setData({
      selectPop:false
    })
  },
  // 点击选择设备
  handleSelect(){
    this.setData({
      selectPop:true
    })
  },
  // 清空定时器
  handleHide() {
    clearInterval(this.data.timer2) // 清空计时器
    this.setData({
      nowTime: '00:00:00', // 计时
      hour: 0,
      minutes: 0,
      seconds: 0
    })
  },
  // 结束训练
  handleEnd(){
    var app = getApp()
    app.globalData.connects = []
    app.globalData.devices.forEach(item => {
      FIG_Ble.Get().BlueOut(item.deviceId)
    })
    this.data.devices.forEach(item => {
      item.flag = false
    })
    this.handleHide()
    this.setData({
      popFlag:false,
      bendNum:0,
      extendNum:0,
      trainFlag:false,
      devices:this.data.devices,
    })
    wx.switchTab({
      url: `/pages/recovery/recovery`,
    })
  },
  // 添加康复动作
  handleSubmit(val,dreg){
    if(val == action) return
     action = val
    const userid = GETSTORAGE('userId')
    const infoid = GETSTORAGE('recoveryMemberInfoId')
    let obj = {
      userId:userid,
      recoveryMemberInfoId:infoid, //康复成员表id
      legAction:val,  //腿部动作
      testTime:util.formatTime(new Date()), //当前时间
      degree:dreg,  //测试角度
      trainLeg:this.data.trainLeg, //测试哪条腿
      thighDevice:'',//大腿设备
      shankDevice:'' //小腿设备
    }
    if(this.data.thighDevice1 != ''){
      obj.thighDevice = this.data.thighDevice1
      obj.shankDevice = this.data.shankDevice2
    }else if(this.data.shankDevice1 != ''){
      obj.thighDevice = this.data.thighDevice2
      obj.shankDevice = this.data.shankDevice1
    }

    console.log(obj,'动作提交数据');
    addRecoveryRecord(obj).then(res => {
      console.log(res,'添加康复动作');
      if(res.data.code == 200){
        if(obj.legAction == '屈'){
          this.setData({
            bendNum:this.data.bendNum+1
          })
         const bendnum = GETSTORAGE('bendCompleteNums')
         let num0 = bendnum + this.data.bendNum
        console.log(num0,'==========num0==========');
         const bendnums = GETSTORAGE('bendNums')
         if(num0>= bendnums){
          this.setData({
            bendFlag:true
          })
        }else{
          this.setData({
            bendFlag:false
          })
        }
        }
        if(obj.legAction == '伸'){
          this.setData({
            extendNum:this.data.extendNum+1
          })
          const extendnum = GETSTORAGE('extendCompleteNums')
          let num1 = extendnum +this.data.extendNum
        console.log(num1,'==========num1==========');
          const extendnums = GETSTORAGE('extendNums')
          if(num1>= extendnums){
            this.setData({
              extendFlag:true
            })
          }else{
            this.setData({
              extendFlag:false
            })
          }
        }
        if(this.data.bendFlag == true && this.data.extendFlag ==true){
          SETSTORAGE('actionOk',true)
          // this.handleEnd()
        }
      }
    })
  },
  // 判断能否开始训练
  ifFlag(){
    var app = getApp()
    let num = 0
    app.globalData.devices.forEach(item => {
      if(item.flag){
        num+=1
      }
    })
    console.log(num);
    console.log(this.data.thighDevice1,this.data.shankDevice2);
    console.log(this.data.shankDevice1,this.data.thighDevice2);
    if(this.data.thighDevice1 != '' && this.data.shankDevice2 != '' && num>=2){
      console.log('通过');
      this.setData({
        trainFlag:true
       })
    } else if(this.data.thighDevice2 != '' && this.data.shankDevice1 != '' && num>=2){
      console.log('通过');
      this.setData({
        trainFlag:true
       })
    }else{
      console.log('不通过');
      this.setData({
        trainFlag:false
       })
    }
    // if(this.data.thighDevice != '' && this.data.shankDevice != ''&& num>=2 && this.data.thighDevice != this.data.shankDevice){
    //  this.setData({
    //   trainFlag:true
    //  })
    // }else{
    //   this.setData({
    //     trainFlag:false
    //    })
    // }
  },
   // 添0 
   toZero(timeNumber) {
    return timeNumber < 10 ? '0' + timeNumber : timeNumber
  },
  // 定时器
  startTimer() {
    this.data.seconds += 1
    if (this.data.seconds >= 60) {
      this.setData({
        seconds: 0,
        minutes: this.data.minutes + 1
      })
    }
    if (this.data.minutes >= 60) {
      this.setData({
        minutes: 0,
        hour: this.data.hour + 1
      })
    }
    this.setData({
      nowTime: `${this.toZero(this.data.hour) + ':' + this.toZero(this.data.minutes) + ':' + this.toZero(this.data.seconds)}`
    })
  },
  // 开始训练
  train(){
    this.data.timer2 = setInterval(this.startTimer, 1000)
    if(!this.data.trainFlag) return
    this.setData({
      popFlag:true
    })
    FIG_Ble.Get().AddBlueChangeHander(

        (res) => {
          console.log(res);
          var value = res.value;
          var deviceId = res.deviceId;
          var text = Cocos_Api_MG.ArrayBufferToStr(value);
          var arr = text.split(" ");
          if (arr[0] != "ba") {
            return;
          }
          var w = Cocos_Api_MG.HexStringTodecimal(arr[5] + arr[4]) / 10000;
          var x = Cocos_Api_MG.HexStringTodecimal(arr[7] + arr[6]) / 10000;
          var y = Cocos_Api_MG.HexStringTodecimal(arr[9] + arr[8]) / 10000;
          var z = Cocos_Api_MG.HexStringTodecimal(arr[11] + arr[10]) / 10000;
          var app = getApp()
          if(app.globalData.devices){
            console.log(app.globalData.devices,'=====app.globalData.devices=======');
              for(let i in app.globalData.devices){
               if(app.globalData.devices[i].deviceId == app.globalData.deviceId1 ){
                 var index1 = i
               }
               if(app.globalData.devices[i].deviceId == app.globalData.deviceId2 ){
                var index2 = i
              }
              }
              if(app.globalData.devices[index1].deviceId ==deviceId){
               var q1 = new Quaternion(w,x,y,z)
                app.globalData.device1 = q1
              }
              if(app.globalData.devices[index2].deviceId == deviceId){
                var q2 = new Quaternion(w,x,y,z)
                app.globalData.device2 = q2
              }
               if(app.globalData.device2 && app.globalData.device1){
            var deg = calculateAngleBetweenQuaternions(app.globalData.device1,app.globalData.device2)
                // console.log(app.globalData.device1,'===========app.globalData.device1==============');
                // console.log(app.globalData.device2,'==============app.globalData.device2============');
                // console.log(deg,'=================deg============');
               
                if(deg > 180){
                  deg = 360 - deg
                }
                // console.log(deg);
            app.globalData.degree = Math.trunc(deg)
          }
          }
        }
      )
      degVal = setInterval(() => {
        this.updataDegree()
      }, 100);
  },

  updataDegree(){
    var app = getApp()
    this.setData({
      degrees:app.globalData.degree
    })
  },
  // 给设备绑定大小腿
  handleBindingLeg0(e){
    console.log('第一个');
    const {value} = e.detail
    const {deviceId} = e.target.dataset.item
    if(value == '小腿'){
      this.setData({
        shankDevice1:deviceId,
        thighDevice1:''
      })
    }else{
      this.setData({
        shankDevice1:'',
        thighDevice1:deviceId
      })
    }
    this.ifFlag()
  },
  // 给设备绑定大小腿
  handleBindingLeg1(e){
    console.log('第二个');
    const {value} = e.detail
    const {deviceId,name} = e.target.dataset.item
    if(value == '小腿'){
      this.setData({
        shankDevice2:deviceId,
        thighDevice2:''
      })
    }else{
      this.setData({
        shankDevice2:'',
        thighDevice2:deviceId
      })
    }
    this.ifFlag()
  },
  // 训练腿部
  handleLeg(e){
    console.log(e);
    const {value} = e.detail
    this.setData({
      trainLeg:value
    })
  },
  // 搜索蓝牙设备
  onInit(){
    if(this.data.searchFlag) return
    app.globalData.connects = []
    app.globalData.devices.forEach(item => {
      FIG_Ble.Get().BlueOut(item.deviceId)
    })
    this.setData({
      searchFlag:true,
      devices:[]
    })
    FIG_Ble.Get().GetNowBlueAll(
      //成功
      function(devices){
        // console.log("=====================成功获取蓝牙设备================")
        // console.log(devices);
        var app = getApp()
        app.globalData.devices = []
        for(let index in devices){
          let device=devices[index];
          if(device.name.indexOf("HMK")!=-1){
            console.log("========找到设备==========",device);
            if(device.connectable){
              app.globalData.devices.push(device)
            }
          }
        }
        console.log(app.globalData.devices,'app.globalData.devices2222');
      },
      //失败
      function(){
        console.log("====================获取蓝牙设备失败=================")
      },
      false);
      setTimeout(() => {
        this.updata()
      }, 2000);
  },
  // 更新设备数组
  updata(){
    this.setData({
      devices:app.globalData.devices
    })
    if(app.globalData.BLEFlag == true){
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请手动开启蓝牙',
      });
      app.globalData.BLEFlag = false
    }
    if(app.globalData.searchFlag == true){
      app.globalData.searchFlag == false
     this.setData({
      searchFlag:false
     })
    }
    if(this.data.devices.length == 2){
        const obj = {
          currentTarget:{
            dataset:{
              item:this.data.devices[0]
            }
          }
        }
        const obj1 = {
          currentTarget:{
            dataset:{
              item:this.data.devices[1]
            }
          }
        }
          this.connect(obj)
         updataVal = obj1
    }
    if(this.data.devices.length > 2){
      this.handleSelect()
    }
  },
  // 连接蓝牙
  connect(e){
    console.log(e,'===============');
    const device = e.currentTarget.dataset.item
    var app = getApp()
    if(app.globalData.deviceId1 == ''){
      app.globalData.deviceId1 = device.deviceId
    }else{
      app.globalData.deviceId2 = device.deviceId
    }
    console.log(app.globalData.deviceId1,'=========app.globalData.deviceId1--487===========');
    console.log(app.globalData.deviceId2,'=========app.globalData.deviceId2--488===========');
    // console.log(device);
    FIG_Ble.Get().BlueTootBydeviceId(device,
      function(obj)
      {
        FIG_Ble.Get().BlueSendTap(Ble_Tools.commands.OnlyQuaternion, null, null, obj);
          console.log("=====获取特征值成功========",obj);
          FIG_Ble.Get().notifyBLE(obj,true);
      },
      function(){});
      setTimeout(() => {
        this.connectStyle()
        this.ifFlag()
      }, 2000);
  },
  //添加已连接flag属性
  connectStyle(){
    var app = getApp()
    let arr = app.globalData.connects
    this.data.devices.forEach(item => {
      for(let i in arr){
        if(item.name == arr[i]){
          item.flag = true
        }
      }
    })
    let newList = this.data.devices.filter(item => item.flag)
    console.log(newList,'newList');
    if(newList.length == 1 && updataVal != ''){
      this.connect(updataVal)
    }
    this.setData({
      devices:this.data.devices,
      okDevices:newList
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    app.util.initWatch(this)
    this.getMedicalRecordInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var app = getApp()
    app.globalData.devices.forEach(item => {
      FIG_Ble.Get().BlueOut(item.deviceId)
    })
    wx.offBLECharacteristicValueChange()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(degVal)
    this.data.devices.forEach(item => {
      item.flag = false
    })
    app.globalData.devices = []
    this.handleHide()
    this.setData({
      popFlag:false,
      bendNum:0,
      extendNum:0,
      trainFlag:false,
      devices:[],
      okDevices:[]
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})